package yunjiao.javatutorials.guava.concurrent.event;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;

/**
 * 错误处理场景
 *
 * @author yangyunjiao
 */
public class EventProcessorErrorExample {
    public static void main(String[] args) throws InterruptedException {
        EventProcessor processor = new EventProcessor();

        ListenableFuture<String> future = processor.sendRequest("REQ-003", "危险操作");

        Futures.addCallback(future, new FutureCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("操作成功: " + result);
            }

            @Override
            public void onFailure(Throwable throwable) {
                System.err.println("操作失败: " + throwable.getMessage());
                // 这里可以添加重试逻辑或错误恢复机制
            }
        }, MoreExecutors.directExecutor());

        // 模拟错误响应
        new Thread(() -> {
            try {
                Thread.sleep(1000);
                processor.handleError("REQ-003", "权限不足，无法执行此操作");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();

        Thread.sleep(2000);
    }
}
